<template>
  <div class="login">
    <van-nav-bar
      title="登录"
    />
    <van-cell-group>
      <van-field
        v-model="mobile"
        center
        required
        clearable
        label="手机号"
        placeholder="请输入手机号"
        :error-message="mobile_errmsg"
        @input="validate"
      />
      <van-field
        v-model="code"
        center
        clearable
        required
        label="短信验证码"
        placeholder="请输入短信验证码"
        :error-message="code_errmsg"
        @input="validate"
      >
        <template #button>
          <van-button size="small" type="primary" @click="sendCode">发送验证码</van-button>
        </template>
      </van-field>
    </van-cell-group>
    <div class="btn-wrap">
      <van-button type="info" @click="login">登录按钮</van-button>
    </div>
    <div class="btn-wrap">
      <van-button type="primary" @click="getUserInfo">获取个人信息</van-button>
    </div>
  </div>
</template>

<script>
import { reqLogin, reqSendCode, reqGetProfile } from '@/api/user.js'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data() {
    return {
      mobile: '13912345678',
      code: '246810',
      mobile_errmsg: '',
      code_errmsg: ''
    }
  },
  methods: {
    ...mapMutations('user', ['setTokenInfo']),
    validate() {
      if (this.mobile.trim() === '') {
        this.mobile_errmsg = 'nm的,会不会输入手机号'
        return false
      }

      if (!/^1\d{10}$/.test(this.mobile)) {
        this.mobile_errmsg = 'nm的,输入正确的手机号码'
        return false
      }

      this.mobile_errmsg = ''
      if (this.code === '') {
        this.code_errmsg = 'nm的,输入验证码啊'
        return false
      }

      if (!/^\d{6}$/.test(this.code)) {
        this.code_errmsg = '输入六位'
        return false
      }
      this.code_errmsg = ''

      return true
    },

    async sendCode() {
      try {
        await reqSendCode(this.mobile)
        this.$toast('发送验证码')
      } catch (e) {
        this.$toast(e.response.data.message)
      }
    },

    async login() {
      if (!this.validate()) {
        return
      }
      this.$toast.loading({
        duration: 0, // 不限时间
        overlay: true,
        message: '加载中...脑瘫',
        forbidClick: true
      })
      try {
        const res = await reqLogin(this.mobile, this.code)
        this.setTokenInfo(res.data)
        this.$toast.success('登录成功')
        const backto = this.$route.query.backto || '/'
        this.$router.push(backto)
      } catch (e) {
        this.$toast(e.response.data.message)
      }
    },

    async getUserInfo() {
      try {
        const res = await reqGetProfile()
        console.log(res)
      } catch (e) {
        this.$toast.fail(e.response.data.message)
      }
    }

  }
}
</script>

<style lang='scss' scoped>
    .login{
        .btn-wrap{
            padding: 20px;
            .van-button{
                width: 100%;
                color: #fff;
                border-radius: 5px;
            }
        }
    }
</style>
